package com.dwxt.parabolic.utils;

import com.alibaba.fastjson.JSONObject;
import com.dwxt.common.util.HttpUtils;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.util.OkHttpUtils;
import com.dwxt.parabolic.base.EventCode;
import com.dwxt.parabolic.entity.Camera;
import com.dwxt.parabolic.entity.Company;
import com.dwxt.parabolic.entity.Event;
import com.dwxt.parabolic.entity.PwInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import static com.dwxt.parabolic.base.EventCode.PARABOLIC;

@Slf4j
public class WxUtil {

    //尚为邻
    static final String SWL_appSecret="2a40884d05ffa101ff03f43eca500ae0";
    static final String SWL_appId="wx14086aaf8b26b639";
    static final String SWL_template_id="4Czwl4KH7UuoBXKKURHLvEjX6jLEQZBy0sbMysn0l3g";
    //苏州
    static final String SZ_appSecret="77a5dafac4806a9d8fcf8dce963df259";
    static final String SZ_appId="wx0478b8bbbb5df49c";
    static final String SZ_template_id="4URwpAcqO9MWTWIK06cCS19hBXSdkDLOVzJC-5A4isA";
    /**
     * 给公众号推送抛物信息
     * 属性	类型	默认值	必填	说明
     * access_token	string		是	接口调用凭证
     * touser	string		是	接收者（用户）的 openid
     * template_id	string		是	所需下发的订阅模板id
     * page	string		否	跳转网页时填写
     * miniprogram	Array.<Objtect>		否	跳转小程序时填写，格式如{ "appid": "pagepath": { "value": any } }
     * data	Object		是	模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
     */
    public static void pushMsgToWx(String openId, Company company, Camera camera, Event event){

        HashMap<String, Object> param = new HashMap<>();
        JSONObject top = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value","您的设备："+camera.getName()+"发出告警信息，请立即查看。");
        top.put("first",first);
        //设备名称
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value",camera.getName());
        top.put("keyword1",keyword1);
        //设备编号
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value",camera.getSerial());
        top.put("keyword2",keyword2);
        //报警时间
        JSONObject keyword3 = new JSONObject();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        keyword3.put("value",df.format(new Date()));
        top.put("keyword3",keyword3);
        //报警防区
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value",company.getName());
        top.put("keyword4",keyword4);
        //报警类型
        JSONObject keyword5 = new JSONObject();
        keyword5.put("value",event.getEventName());
        top.put("keyword5",keyword5);
        //remark
        JSONObject remark = new JSONObject();
        remark.put("value","点此消息可查看抛物视频");
        top.put("remark",remark);
        param.put("touser",openId);
        param.put("template_id",SZ_template_id);
        param.put("data",top);
        param.put("url","http://118.178.180.213/wssq/parabolic/app/index.html?id="+event.getId());
        System.out.println(JsonUtils.objectToJson(param));
        String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(), JsonUtils.objectToJson(param), null);
        log.info("发送模板返回："+s);
    }

    /**
     * 获取access_token
     */
    private static String getAccessToken(){
        String wx_access_token = RedisUtil.get("wx_access_token", String.class);
        if (!StringUtils.isNotEmpty(wx_access_token)){
            return refreshAccessToken();
        }
        return wx_access_token;
    }

    /**
     * 刷新access_token
     */
    private static String refreshAccessToken(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("grant_type","client_credential");
        param.put("appid",SZ_appId);
        param.put("secret",SZ_appSecret);
        String request = HttpUtils.getRequest("https://api.weixin.qq.com/cgi-bin/token", param);
        JSONObject jsonObject1 = JSONObject.parseObject(request);
        String access_token = jsonObject1.get("access_token").toString();
        RedisUtil.set("gkpw_wx_access_token",access_token,Long.parseLong(jsonObject1.get("expires_in").toString())-5);
        log.info("gkpw_wx_access_token:"+access_token);
        log.info("获取access_token："+request);
        return access_token;
    }
}
